package com.gougou.search.controller;

import com.gougou.search.entity.SearchResult;
import com.gougou.search.service.ItemSearchService;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ClassName SearchController
 * @Description
 * @Author c
 * @Date 2018/9/14 11:41
 * @Vcrsion 1.0
 **/
@Controller
public class SearchController {

    private static final Integer ROWS = 16;

    // solr数据交互地址
    private static final String URL = "http://132.232.50.106:8983/gougou";

    private ItemSearchService itemSearchService ;

    SearchController(){
        HttpSolrServer httpSolrServer = new HttpSolrServer(URL);
        httpSolrServer.setParser(new XMLResponseParser()); // 设置响应解析器
        httpSolrServer.setMaxRetries(1); // 设置重试次数，推荐设置为1
        httpSolrServer.setConnectionTimeout(1000); // 建立连接的最长时间
        this.itemSearchService = new ItemSearchService(httpSolrServer);
    }

    @RequestMapping(value =  "search", method = RequestMethod.GET)
    public ModelAndView search(@RequestParam(value = "q",defaultValue = "*") String keyWords, @RequestParam(value = "page", defaultValue = "1") Integer page){
        ModelAndView mv = new ModelAndView("search");


        // 搜索关键字
        mv.addObject("query", keyWords);

        SearchResult searchResult = null;
        try {
            searchResult = itemSearchService.search(keyWords, page, ROWS);
        } catch (SolrServerException e) {
            e.printStackTrace();
            searchResult = new SearchResult(0L, null);
        }

        // 搜索结果数据
        mv.addObject("itemList", searchResult.getList());
        // 页数
        mv.addObject("page", page);

        int total = searchResult.getTotal().intValue();
        int pages = total % ROWS == 0 ? total / ROWS : total / ROWS + 1;

        // 总页数
        mv.addObject("pages", pages);
        return  mv;
    }
}
